package com.huangmb.anymark.app.api;

import android.content.Context;
import android.support.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.android.volley.*;
import com.android.volley.toolbox.Volley;
import com.huangmb.androidlib.utils.Logger;
import com.huangmb.anymark.app.net.HttpRequest;
import com.huangmb.anymark.app.net.RequestParameter;
import com.huangmb.anymark.app.api.mock.UserApiMock;
import com.huangmb.anymark.app.app.AnyMarkApplication;
import com.huangmb.anymark.app.model.User;
import org.jsoup.Connection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hmb
 * @version 1.0
 * @since 2016/4/20 15:02
 */
public class UsersApi extends BaseApi {

    private static boolean isMock = false;
    private final static String BASE_PATH = API_SERVER + "/user";

    private final static String API_LOGIN = BASE_PATH + "/login";
    private final static String API_LOGOUT = BASE_PATH + "/logout";
    private final static String API_REGISTER = BASE_PATH + "/register";

    public static void login(final String name, final String password, Listener listener) {
        /*if (isMock) {
            UserApiMock.login(name, password, listener);
            return;
        }
*/
        Map<String,String> params = new HashMap<>();
        params.put("name", name);
        params.put("password", password);

        execute(API_LOGIN, Connection.Method.POST, params, listener);

    }

    /**
     *
     */
    public static void logout() {
        final Listener listener = new AbsListener() {
            @Override
            public boolean onRawData(String result) {
                //2.清空本地cookies
                clearCookie();
                return true;
            }
        };
        if (isMock) {
            UserApiMock.logout(listener);
            return;
        }
        //3.清空用户上下文
        AnyMarkApplication.getInstance().setUserContext(null);
        //1.发起登出请求
        execute(API_LOGOUT, Connection.Method.GET, null, listener);

        Logger.d("UserApi","退出");
    }

    /**
     * 注册账户
     *
     * @param listener 回调
     */
    public static void register(@NonNull User user, Listener listener) {
        if (isMock) {
            UserApiMock.register(user, listener);
            return;
        }
        Map<String,String> params = new HashMap<>();
        params.put("name",user.getName());
        params.put("password",user.getPassword());
        params.put("sex",user.getSex().toString());
        execute(API_REGISTER, Connection.Method.POST, params, listener);
    }
}
